#!/bin/bash

readonly PROG_DIR=$(pwd)
readonly PID_FILE=$PROG_DIR/asch.pid
readonly IPS=(
  "http://china.aschcdn.com-China"
  "http://asia.aschcdn.com-Asia"
  "http://america.aschcdn.com-America"
  "http://europe.aschcdn.com-Europe"
  )

function read_port() {
  echo `cat $PROG_DIR/config.json |grep '"port"'|head -n 1| awk -F "[:,]" '{print$2}'|tr -d ' '`
}

function is_running() {
  test -f $PID_FILE && ps -p $(cat $PID_FILE) > /dev/null
}

function status() {
  if is_running; then
    echo "Asch server is running"
  else
    echo "Asch server is not running"
  fi
}

function start() {
  if is_running; then
    echo "Asch server has already started"
  else
    rm -f $PROG_DIR/asch.pid
    node $PROG_DIR/app.js --base $PROG_DIR --daemon $@
  fi
}

function stop() {
  local pid
  if test -f $PID_FILE; then
    pid=$(cat $PID_FILE)
  fi
  if [ -n "$pid" ] && ps -p "$pid" > /dev/null; then
    kill $pid
    sleep 1
    i=1
    while ps -p $pid > /dev/null; do
      if [ $i == 5 ]; then
        kill -9 $pid
        echo "Asch server killed"
      fi
      echo "Still waiting for asch server to stop ..."
      sleep 1
      ((i++))
    done
    echo "Asch server stopped"
  else
    echo "Asch server is not running"
  fi
  rm -f $PID_FILE
}

function restart() {
  stop
  start
}

function getnettype(){
  magic=$(cat $PROG_DIR/config.json | grep magic | awk -F: '{print $2}' | cut -d \" -f2)
  if [ "$magic" = "594fe0f3" ]; then
    net="testnet"
  elif [ "$magic" = "5f5b3cf5" ]; then
    net="mainnet"
  fi 
  echo "net is $net"
}

function choosenode(){
  read -p "Please input your choice [default 0] : "  num
  num=${num:-0}

  if [ $num -ge $length ];then
    echo "Invalid number, please run aschd again and choose another node!"
    exit 1
  fi

  if [ i${status[$num]} = i"N" ];then
    echo "This node has no data,please run aschd again and choose another node!"
    exit 2
  fi

  ip=$(echo ${IPS[$num]} | awk -F- '{print $1}')
  var=$(curl -sL -m 10 "$ip/$meta_file")
  Name=$(echo $var| awk '{print $1}')
  Md5=$(echo $var| awk '{print $2}')
}

function rebuild() {
  getnettype
  meta_file=metadata_rebuild_$net.txt

  echo "Please select one of the following sources to use"
  length=${#IPS[@]}
  for i in $(seq 0 $[ $length-1 ])
  do
    # echo ${IPS[$i]}
    ip=$(echo ${IPS[$i]} | awk -F- '{print $1}')
    country=$(echo ${IPS[$i]} | awk -F- '{print $2}')
    memo="$country users recommended"

    cnt=1
    var=$(curl -sL -m 10 $ip/$meta_file)
    if [ $? -eq 0 ];then
      cnt=$(echo $var | grep html | wc -l)
    fi
    if [ $cnt -eq 0 ];then
      status[$i]="Y"
      Name=$(echo $var| awk '{print $1}')
      Md5=$(echo $var| awk '{print $2}')
      Date=$(echo $var| awk '{print $3}')
      Height=$(echo $var| awk '{print $4}')
      Size=$(echo $var| awk '{print $5}')
      DB=$(echo $var| awk '{print $6}')
      echo $i. $ip [$memo]  "Height:"$Height "Date:"$Date "Size:"$Size
    else
      status[$i]="N"
      memo="No data,do not use."
      echo $i. $ip [$memo]
    fi
  done

  choosenode

  echo "Downloading blockchain snapshot $Name..."
  /bin/rm $Name
  wget "$ip/$Name"
  newMd5=$(md5sum $Name | awk '{print $1}')
  if [ i$newMd5 = i$Md5 ];then
    echo "Check md5 passed!"
  else
    echo "Check md5 failed,please run again!"
        exit
  fi

  ./aschd stop
  rm -rf ./data
  echo "Extracting snapshot..."
  tar zxf $Name
  #./aschd start
}

function version() {
  node $PROG_DIR/app.js --version
}

function check_os() {
  os_num=`cat /etc/os-release | grep '\"Ubuntu\"'  | wc -l`
  if [ $os_num -ne 1 ];then
    echo "Linux is not Ubuntu, please configure manually!" && exit 1
  fi
}

function configure() {
  check_os
  sudo bash $PROG_DIR/init/install_deps.sh
  sudo bash $PROG_DIR/init/config_ntp.sh
  sudo bash $PROG_DIR/init/config_monitor.sh
}

function upgrade() {
  getnettype
  meta_file=metadata_upgrade_$net.txt

  echo "Please select one of the following sources to use"
  length=${#IPS[@]}
  for i in $(seq 0 $[ $length-1 ])
  do
    # echo ${IPS[$i]}
    ip=$(echo ${IPS[$i]} | awk -F- '{print $1}')
    country=$(echo ${IPS[$i]} | awk -F- '{print $2}')
    memo="$country users recommended"

    #echo $ip $net
    cnt=1
    var=$(curl -sL -m 10 "$ip/$meta_file")
    if [ $? -eq 0 ];then
    cnt=$(echo $var | grep html | wc -l)
    fi
    if [ $cnt -eq 0 ];then
      status[$i]="Y"
      Name=$(echo $var| awk '{print $1}')
      Md5=$(echo $var| awk '{print $2}')
      Date=$(echo $var| awk '{print $3}')
      Version=$(echo $var| awk '{print $4}')
      Size=$(echo $var| awk '{print $5}')

      echo $i. $ip [$memo] "Version:"$Version "Date:"$Date  "Size:"$Size
    else
      status[$i]="N"
      memo="No data,do not use."
      echo $i. $ip [$memo]
    fi
  done
  # echo "status",${status[*]}

  choosenode

  mkdir -p tmp
  wget "$ip/$Name" -O tmp/$Name
  newMd5=$(md5sum tmp/$Name | awk '{print $1}')
  if [ i$newMd5 = i$Md5 ];then
    echo "Check md5 passed!"
  else
    echo "Check md5 failed,please run again!"
    exit
  fi

  echo "Extracting new package ..."
  tar zxf tmp/$Name -C tmp/
  extractedDir=`find tmp -maxdepth 1 -type d | grep asch |head -n 1`
  currentVersion=`./aschd version`
  chmod u+x $extractedDir/aschd
  ./aschd stop
  echo "Copying new files ..."
  for file in `ls $extractedDir`
  do
    if [ "$file" != "config.json" ]; then
    echo "copy $extractedDir/$file ..."
    cp -r $extractedDir/$file ./
    fi
  done
  rm -rf $extractedDir tmp/$latestName
  newVersion=`./aschd version`
  echo "Upgrade to $newVersion done."
  #./aschd start
}

function enable() {
  local secret="$@"
  local port=`read_port`
  curl -k -H "Content-Type: application/json" -X POST -d '{"secret":"'"$secret"'"}' localhost:$port/api/delegates/forging/enable
}

function main() {
  export PATH=$PROG_DIR/bin:$PATH
  local cmdType=`type -t $1`
  if [ $cmdType == "function" ]; then
    eval $@
  else
    echo "Command not supported"
  fi
}

main $@
